#include "logger.h"
#include <time.h>
#include <sstream>
#include <fstream>
#include <iostream>

const char* logger_lvl_strings[] =  {
  "(Info)    ",
  "(Debug)   ",
  "(Warning) ",
  "(Error)   ",
  "(Fatal)   "
};

ostream* logfile = NULL;
logger_quit_callback user_callback = NULL;
bool inside_line = false;
bool flush_log = true;
int exit_status = EXIT_SUCCESS;

void logger_init (const char* logfilename, logger_quit_callback callback) {
  // Assign the user specific quit callback.
  user_callback = callback;

  // Needed to build strings with parameters.
  stringstream ss;
  
  // If not specified, use the logfile set in LOGFILE.
  if ((logfilename == NULL) || (strlen(logfilename) == 0)) {
    logfile = &cout;
    ss << "No logfile was specified, using : " << LOGFILE << " instead.";
    LOG_INFO(ss.str());
    logfilename = LOGFILE;
  }
  
  ofstream* ofs = new ofstream;
  // Attempt to open in append mode.
  ofs->open(logfilename, ios_base::app);
  // Check if we succeeded.
  if (!ofs) {
    // Failed to open : report a fatal error on the stderr (and hence quit).
    delete ofs;
    logfile = &cerr;
    ss.str("");
    ss << "Unable to open the logfile : " << logfile;
    LOG_FATAL(ss.str());
  }
  else {
    logfile = ofs;
  }

  /**
    * Log the current date and time.
    */
  time_t now;
  time(&now);
  LOGN ("Logger started ");
  char* str = ctime(&now);
  str[strlen(str) - 1] = '\0';
  LOG (str);
}

void logger_quit () {
  /**
    * Log a termination message with date and time.
    */
  time_t now;
  time(&now);
  LOGN ("Logger terminated ");
  char* str = ctime(&now);
  str[strlen(str) - 1] = '\0';
  LOG (str);

  /**
    * Close the file handler.
    */
  (static_cast<ofstream*>(logfile))->close();

  /**
    * Finally call the user defined quit callback if any.
    */
  if (user_callback != NULL) {
    user_callback(exit_status);
  }
}

